package com.andrewdashin.twit2jabber.jobs;

import com.andrewdashin.twit2jabber.dao.UserDao;
import com.andrewdashin.twit2jabber.domain.User;
import com.andrewdashin.twit2jabber.services.JabberService;
import com.andrewdashin.twit2jabber.services.TwitterService;
import org.jivesoftware.smack.Chat;
import org.jivesoftware.smack.MessageListener;
import org.jivesoftware.smack.packet.Message;
import org.springframework.beans.factory.annotation.Required;
import org.springframework.transaction.annotation.Transactional;
import winterwell.jtwitter.Twitter;
import winterwell.jtwitter.TwitterException;


/**
 * User: dashin
 * Date: 26.11.2009
 * Time: 11:03:59
 */
public class TwitMeJob {
    private JabberService jabberService;
    private TwitterService twitterService;
    private UserDao userDao;

    @Transactional
    public void checkForTwits() {
        for (User user: userDao.findAllActive()) {
            try {
                for (Twitter.Status message: twitterService.getNewTwits(user)) {
                    jabberService.sendMessage(user.getJabberUserName(), message.getUser().getScreenName() + ": " + message.getText(), new MessageListener() {
                        @Override
                        public void processMessage(Chat chat, Message message) {
                            doProcessCallback(chat, message);
                        }
                    });
                }
            } catch (TwitterException e) {
                jabberService.sendMessage(user.getJabberUserName(), twitterService.getFriendlyMessage(e), null);
            }
        }
    }

    // TODO - make it happen on all messages. Not only from users we alreaady have chat with!!!
    private void doProcessCallback(Chat chat, Message message) {
        if (message.getBody().trim().startsWith("!")) {
            doProcessSystemCommand(chat, message);
        } else {
            User user = userDao.findByJabberUserName(message.getFrom());
            if (user != null) {
                try {
                    twitterService.newStatus(user, message.getBody());
                } catch (TwitterException e) {
                    jabberService.sendMessage(user.getJabberUserName(), twitterService.getFriendlyMessage(e), null);
                }
            }
        }
    }

    private void doProcessSystemCommand(Chat chat, Message message) {
        // TODO implement system commands:
        // * help
        // * Registration
        // * UnRegistration
        // * Switch to active/passive states
    }

    @Required
    public void setJabberService(JabberService jabberService) {
        this.jabberService = jabberService;
    }

    @Required
    public void setTwitterService(TwitterService twitterService) {
        this.twitterService = twitterService;
    }

    @Required
    public void setUserDao(UserDao userDao) {
        this.userDao = userDao;
    }

}
